﻿//#define _CRT_SECURE_NO_WARNINGS
// C/C++ 标准库学习网站：https://legacy.cplusplus.com
// C/C++ 参考学习网站：https://zh.cppreference.com/w/cpp
// C/C++ 微软(Visual Studio)中文学习网站：https://learn.microsoft.com/zh-cn/cpp/cpp/?view=msvc-170
// OpenGl 学习网站：https://docs.gl/
#include "common.h" // 包含预编译头文件

#include "MyWindow.h"
#include <QSet>

void MyWindow::keyPressEvent(QKeyEvent* event)
{
    if (my_player)
    {
        int key = event->key();
        if (key == Qt::Key_Space) {
            if (my_player->is_playing) {
                my_player->pause();
                my_player->is_playing = false;
            }
            else {
                my_player->play();
                my_player->is_playing = true;
            }
        }
        else if (key == Qt::Key_J) {
            keyLeftHoldSlot();
            timerLeft->start(300);
        }
        else if (key == Qt::Key_L) {
            keyRightHoldSlot();
            timerRight->start(300);
        }

    }

    /*
    else if (event->key() == Qt::Key_B) {
        qDebug() << "press B key";
    }
    else {
        qDebug() << "press other key" << event->key();
    }
    */

    QWidget::keyPressEvent(event);  // 确保调用基类的keyPressEvent方法
}

void MyWindow::keyReleaseEvent(QKeyEvent* event)
{
    if (my_player)
    {
        int key = event->key();
        if (key == Qt::Key_J) {
            timerLeft->stop();
        }
        else if (key == Qt::Key_L) {
            timerRight->stop();
        }
    }

}

void MyWindow::keyLeftHoldSlot()
{
    if (audio_tempo <= 0.5f)
        return;

    audio_tempo -= 0.1f;
    my_player->set_audio_tempo(audio_tempo);
}

void MyWindow::keyRightHoldSlot()
{
    if (audio_tempo >= 5.0f)
        return;

    audio_tempo += 0.1f;
    my_player->set_audio_tempo(audio_tempo);
}

bool MyWindow::eventFilter(QObject* obj, QEvent* event)
{
    // 鼠标滚轮处理监听器 Slider
    if ((obj == ui->horizontalSlider_listenerX ||
        obj == ui->horizontalSlider_listenerY ||
        obj == ui->horizontalSlider_listenerZ) &&
        event->type() == QEvent::Wheel) {
        QSlider* slider = qobject_cast<QSlider*>(obj);
        if (slider) {
            QWheelEvent* wheelEvent = static_cast<QWheelEvent*>(event);
            int numSteps = wheelEvent->angleDelta().y() / 120; // 一步 120
            int newValue = slider->value() + numSteps * slider->singleStep();
            newValue = std::max(slider->minimum(), std::min(slider->maximum(), newValue));
            slider->setValue(newValue);
            return true; // 已处理
        }
    }
    // verticalSlider_fXXX 悬停或拖动时显示值（分贝）
    QSet<QObject*> eqSliderObjs = {
        ui->verticalSlider_f62,
        ui->verticalSlider_f125,
        ui->verticalSlider_f250,
        ui->verticalSlider_f500,
        ui->verticalSlider_f1000,
        ui->verticalSlider_f2000,
        ui->verticalSlider_f4000,
        ui->verticalSlider_f8000,
        ui->verticalSlider_f16000
    };
    // 禁用 verticalSlider_fXXX 的鼠标滚轮事件
    if (eqSliderObjs.contains(obj) && event->type() == QEvent::Wheel) {
        return true; // 直接拦截，不处理
    }
    if (eqSliderObjs.contains(obj)) {
        QSlider* slider = qobject_cast<QSlider*>(obj);
        if (slider) {
            float dbValue = slider->value() / 10.0f;
            QString tip = QString::number(dbValue, 'f', 1) + QString::fromUtf8("分贝");
            if (event->type() == QEvent::MouseMove || event->type() == QEvent::HoverMove || event->type() == QEvent::Enter) {
                QPoint globalPos = slider->mapToGlobal(slider->rect().center());
                QToolTip::showText(globalPos, tip, slider);
            } else if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) {
                QPoint globalPos = slider->mapToGlobal(slider->rect().center());
                QToolTip::showText(globalPos, tip, slider);
            } else if (event->type() == QEvent::Leave) {
                QToolTip::hideText();
            }
        }
    }
    // 右键菜单处理frame_1~frame_9
    if ((obj == ui->frame_1 || obj == ui->frame_2 || obj == ui->frame_3 || obj == ui->frame_4 ||
        obj == ui->frame_5 || obj == ui->frame_6 || obj == ui->frame_7 || obj == ui->frame_8 || obj == ui->frame_9)
        && event->type() == QEvent::ContextMenu) {
        QContextMenuEvent* contextEvent = static_cast<QContextMenuEvent*>(event);
        // 复用 groupBoxReverb 的菜单逻辑
        onGroupBoxReverbContextMenuRequested(ui->groupBoxReverb->mapFromGlobal(contextEvent->globalPos()));
        return true;
    }

    // 音量和速度控制，需要修改哦
    if (obj == ui->pushButtonVolume || obj == sliderVolume || obj == labelVolume) {
        if (event->type() == QEvent::Enter) {
            volumeAreaHovered = true;
            if (hideVolumeTimer && hideVolumeTimer->isActive())
                hideVolumeTimer->stop();
            if (!sliderVolume) {
                sliderVolume = new QSlider(Qt::Vertical, this);
                sliderVolume->setRange(0, 200);
                sliderVolume->setValue(100);
                sliderVolume->setFixedWidth(ui->pushButtonVolume->width());
                sliderVolume->setFixedHeight(150);
                connect(sliderVolume, &QSlider::valueChanged, [this](int value) {
                    if (labelVolume)
                        labelVolume->setText(QString(u8"%1%").arg(value));
                    if (my_player)
                        my_player->set_volume(value);
                });
                sliderVolume->installEventFilter(this);
            }
            if (!labelVolume) {
                labelVolume = new QLabel(QString(u8"%1%").arg(sliderVolume->value()), this);
                labelVolume->setAlignment(Qt::AlignCenter);
                labelVolume->setFixedWidth(ui->pushButtonVolume->width());
                labelVolume->setFixedHeight(15);
                labelVolume->installEventFilter(this);
            }
            QPoint pos = ui->pushButtonVolume->mapTo(this, QPoint(0, -sliderVolume->height() - labelVolume->height() + 15));
            sliderVolume->move(pos);
            labelVolume->move(pos.x(), pos.y() - labelVolume->height());
            sliderVolume->show();
            labelVolume->show();
        }
        else if (event->type() == QEvent::Leave) {
            volumeAreaHovered = false;
            if (!hideVolumeTimer) {
                hideVolumeTimer = new QTimer(this);
                hideVolumeTimer->setSingleShot(true);
                connect(hideVolumeTimer, &QTimer::timeout, [this]() {
                    if (!volumeAreaHovered) {
                        if (sliderVolume) sliderVolume->hide();
                        if (labelVolume) labelVolume->hide();
                    }
                    hideVolumeTimer->stop();
                });
            }
            hideVolumeTimer->start(500);
        }
        else if (event->type() == QEvent::Wheel) {
            QWheelEvent* wheelEvent = static_cast<QWheelEvent*>(event);
            int delta = wheelEvent->angleDelta().y() / 120;
            int value = sliderVolume->value() + delta * 2;
            sliderVolume->setValue(qBound(0, value, 200));
            return true;
        }
        return false;
    }
    else if (obj == ui->pushButtonSpeed || obj == sliderSpeed || obj == labelSpeed) {
        if (event->type() == QEvent::Enter) {
            speedAreaHovered = true;
            if (hideSpeedTimer && hideSpeedTimer->isActive())
                hideSpeedTimer->stop();
            if (!sliderSpeed) {
                sliderSpeed = new QSlider(Qt::Horizontal, this);
                sliderSpeed->setRange(50, 500);
                sliderSpeed->setValue(100);
                sliderSpeed->setFixedWidth(150);
                connect(sliderSpeed, &QSlider::valueChanged, [this](int value) {
                    float speed = value / 100.0f;
                    if (labelSpeed)
                        labelSpeed->setText(QString(u8"速度: %1x").arg(speed, 0, 'f', 2));
                    if (my_player)
                        my_player->set_audio_tempo(speed);
                });
                sliderSpeed->installEventFilter(this);
            }
            if (!labelSpeed) {
                labelSpeed = new QLabel(QString(u8"速度: %1x").arg(sliderSpeed->value() / 100.0f, 0, 'f', 2), this);
                labelSpeed->installEventFilter(this);
            }
            QPoint pos = ui->pushButtonSpeed->mapTo(this, QPoint(0, -sliderSpeed->height() - labelSpeed->height() + 25));
            sliderSpeed->move(pos);
            labelSpeed->move(pos.x(), pos.y() - labelSpeed->height());
            sliderSpeed->show();
            labelSpeed->show();
        }
        else if (event->type() == QEvent::Leave) {
            speedAreaHovered = false;
            if (!hideSpeedTimer) {
                hideSpeedTimer = new QTimer(this);
                hideSpeedTimer->setSingleShot(true);
                connect(hideSpeedTimer, &QTimer::timeout, [this]() {
                    if (!speedAreaHovered) {
                        if (sliderSpeed) sliderSpeed->hide();
                        if (labelSpeed) labelSpeed->hide();
                    }
                    hideSpeedTimer->stop();
                });
            }
            hideSpeedTimer->start(500);
        }
        else if (event->type() == QEvent::Wheel) {
            QWheelEvent* wheelEvent = static_cast<QWheelEvent*>(event);
            int delta = wheelEvent->angleDelta().y() / 120;
            int value = sliderSpeed->value() + delta * 2;
            sliderSpeed->setValue(qBound(50, value, 500));
            return true;
        }
        return false;
    }
    return QMainWindow::eventFilter(obj, event);
}

void MyWindow::closeEvent(QCloseEvent* event)
{
    if (my_player) {
        my_player->pause();
        my_coord_thread->stopThread();
    }
}
